package com.ja.openchat.ui.chat.adapter.viewholder;

import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.ConversationFragment;
import com.ja.openchat.ui.chat.annotation.EnableContextMenu;
import com.ja.openchat.ui.chat.annotation.MessageContentType;
import com.ja.openchat.ui.chat.annotation.MessageContextMenuItem;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.model.message.MessageContent;
import com.zy.openchat.core.model.message.UiMessage;
import com.zy.openchat.util.SpeechRecognizerUtil;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@MessageContentType(TelegramManager.MessageType.MessageType_Audio)
@EnableContextMenu
public class AudioMessageContentViewHolder extends MediaMessageContentViewHolder {
    @BindView(R.id.audioImageView)
    ImageView ivAudio;
    @BindView(R.id.durationTextView)
    TextView durationTextView;
    @BindView(R.id.audioContentLayout)
    View contentLayout;
    @BindView(R.id.seekBar)
    SeekBar seekBar;
    @BindView(R.id.transferTextView)
    TextView transferTextView;
    @BindView(R.id.transferView)
    View transferView;
    @BindView(R.id.transferProgress)
    View transferProgress;


    public AudioMessageContentViewHolder(ConversationFragment fragment, RecyclerView.Adapter adapter, View itemView) {
        super(fragment, adapter, itemView);
    }

    @Override
    public void onBind(UiMessage message) {
        super.onBind(message);
        MessageContent voiceMessage = message.message.content;
        durationTextView.setText(voiceMessage.audio.duration + "''");
        messageViewModel.messageUpdateLiveData().observeForever(new Observer<UiMessage>() {
            @Override
            public void onChanged(UiMessage uiMessage) {
                if (uiMessage != null && uiMessage.totalLenght > 0) {
                    seekBar.setSecondaryProgress(uiMessage.secendProssed);
                    seekBar.setProgress(uiMessage.currentPosition);
                    if (!message.isPlaying) {
                        seekBar.setProgress(0);
                        ivAudio.setActivated(message.isPlaying);
                    }
                }
            }
        });
        ivAudio.setActivated(message.isPlaying);
        // 下载完成，开始播放
        if (message.progress == 100) {
            message.progress = 0;
            seekBar.setProgress(message.progress);
            itemView.post(() -> {
                messageViewModel.playAudioMessage(message);
            });
        }
        seekBar.setClickable(false);
        seekBar.setEnabled(false);
        seekBar.setFocusable(false);
        seekBar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //直接消费掉触摸事件
                return true;
            }
        });
        if(TextUtils.isEmpty(message.transferVocieText)){
            transferView.setVisibility(View.GONE);
        }else{
            transferTextView.setText(message.transferVocieText);
            transferTextView.setVisibility(View.VISIBLE);
            transferView.setVisibility(View.VISIBLE);
        }
        if(!message.message.isAudioFileDownloaded()){
            TelegramManager.getTelegramManager().downloadFile(message.message.chat_id + "_" + message.message.id, message.message.getAudioFileId(), 0, TelegramManager.FileType.FileType_Message_Audio);
        }
    }

    @Override
    public void onViewRecycled() {
        // TODO 可实现语音是否持续播放、中断登录逻辑
    }

    @OnClick({R.id.audioContentLayout, R.id.audioImageView})
    public void onClick(View view) {
        if (!message.message.isAudioFileDownloaded()) {
            message.isDownloading = true;
            TelegramManager.getTelegramManager().downloadFile(message.message.chat_id + "_" + message.message.id, message.message.getAudioFileId(), 0, TelegramManager.FileType.FileType_Message_Audio);
            return;
        }
        messageViewModel.playAudioMessage(message);
    }


    @MessageContextMenuItem(tag = MessageContextMenuItemTags.TAG_VOICE_TRANSFER_TEXT, confirm = false, priority = 10)
    public void transferText(View itemView, UiMessage message) {
        if(!TextUtils.isEmpty(message.transferVocieText)){
            transferTextView.setText(message.transferVocieText);
            transferProgress.setVisibility(View.GONE);
            transferView.setVisibility(View.VISIBLE);
            return;
        }
        if (!message.message.isAudioFileDownloaded()) {
            ToastUtils.showShort(fragment.getString(R.string.downloading_try_again));
            return;
        }
        transferTextView.setVisibility(View.GONE);
        transferView.setVisibility(View.VISIBLE);
        transferProgress.setVisibility(View.VISIBLE);
        SpeechRecognizerUtil.getInstance()
                .recognizer(message.message.audioLocalPath())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String text) {
                        message.transferVocieText = TextUtils.isEmpty(text)?fragment.getString(R.string.conversion_no_results):text;
                        transferTextView.setText(message.transferVocieText);
                        transferTextView.setVisibility(View.VISIBLE);
                        transferProgress.setVisibility(View.GONE);
                    }

                    @Override
                    public void onError(Throwable e) {
                        message.transferVocieText = e.getMessage();
                        transferTextView.setText(message.transferVocieText);
                        transferTextView.setVisibility(View.VISIBLE);
                        transferProgress.setVisibility(View.GONE);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
